package com.atguigu.flow.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.flow.entity.Items;
import com.atguigu.flow.entity.ItemsQuote;
import com.atguigu.flow.entity.SysAttachment;
import com.atguigu.flow.entity.vo.Module_Field;
import com.atguigu.flow.entity.vo.Noclude_Field;
import com.atguigu.flow.entity.vo.Permissions;
import com.atguigu.flow.mapper.ItemsMapper;
import com.atguigu.flow.mapper.ItemsQuoteMapper;
import com.atguigu.flow.mapper.SysAttachmentMapper;
import com.atguigu.flow.mapper.SysRoleMapper;
import com.atguigu.flow.service.ItemsService;
import com.atguigu.flow.utils.AttachmentSave;
import com.atguigu.flow.utils.GetFlowModule_field_util;
import com.atguigu.flow.utils.Workflow;
import com.atguigu.flow.utils.Zxb_receivedata;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-03-20
 */
@Service
public class ItemsServiceImpl extends ServiceImpl<ItemsMapper, Items> implements ItemsService {
    @Autowired
    private
    Workflow workflow;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private ItemsMapper itemsMapper;
    @Autowired
    private ItemsQuoteMapper itemsQuoteMapper;




    @Autowired
    private SysAttachmentMapper sysAttachmentMapper;
    @Autowired
    private AttachmentSave attachmentSave;
    @Autowired
    GetFlowModule_field_util getFlowModule_field_util;


    @Override
    public
    JSONObject itemsshowlist(String modulename, String recordid, String username) throws Exception {
        JSONObject json = new JSONObject();
        JSONArray jsonArray=new JSONArray();
        JSONArray jsonArray1=new JSONArray();
        JSONArray jsonArray2=new JSONArray();
        //读取数据库权限列表
        List<Permissions> permissionsList = sysRoleMapper.get_role_Permissions(username);
        json.put("fields", jsonArray1);
        json.put("roles", jsonArray2);
        System.out.println(json);
        int i = 0;
        try {
            for (i = 0; i < permissionsList.size(); i++) {
                //读取数据库权限字段（Permissions）为字节字段，读到字节流并转为string
                Permissions permissions = permissionsList.get(i);
                System.out.println(permissions.getOrganizationID());
                byte[] datas = permissions.getPermissions();

                String filepath = "";

                if (datas != null) {

                    ByteArrayOutputStream baos = null;


                    // create new ByteArrayOutputStream
                    baos = new ByteArrayOutputStream();

                    // write byte array to the output stream
                    baos.write(datas);

                    // converts buffers using default character set
                    String str = baos.toString();

                    if(baos!=null)
                        baos.close();

                    //Permissions为xml文件，解析xml文件，查找对应模块的数据范围及对应模块的隐藏字段列表
                    Workflow.readperxml(str, modulename, permissions.getOrganizationID(), json);
                }

            }      // print
            System.out.println(json);

            List<Noclude_Field> noSelectedlist = new ArrayList<Noclude_Field>();
            //对应模志的主子表数据集字段的名称、模块名.字段名，表名，字段数据名，是否子表
            List<Module_Field> module_fieldList = Workflow.getmodle_fieldlist(modulename);
            jsonArray = json.getJSONArray("fields");//读隐藏字段列表
            List<Module_Field> module_fieldList_temp = new ArrayList<Module_Field>();
            for (i = 0; i < jsonArray.size(); i++) {

                //读出隐藏字段列表中的字段名称（模块名.字段名)
                String module_fieldname = jsonArray.getJSONObject(i).getString("fieldname");
                //隐藏字段匹配模块集的字段，如果匹配添加到不包含字段列表中（包括名称，及数据库字段名)
                module_fieldList_temp = module_fieldList.stream().filter(user -> module_fieldname.equals(user.getModule_field_name())).collect(Collectors.toList());

                //System.out.println(module_fieldList_temp);
                if (module_fieldList_temp.size() > 0) {


                    Module_Field module_field = module_fieldList_temp.get(0);
                    Noclude_Field noclude_field = new Noclude_Field();
                    noclude_field.setFieldname(module_field.getFieldname());
                    noclude_field.setTablename(module_field.getTablename());
                    noSelectedlist.add(noclude_field);


                }
            }
            //System.out.println(noSelectedlist);
            QueryWrapper<Items> wrapper = new QueryWrapper<>();

            //LambdaQueryWrapper<Items> queryWrapper = Wrapper.lambdaQuery(Items.class);
            //把隐藏字段放在querywrapper中
            if (noSelectedlist.size() > 0) {

                String[] aa = new String[]{"Created", "HaveAttachment", "Archived", "HaveReminder", "Photo"};
                List<String> noselectlist = Zxb_receivedata.nofieldlist(noSelectedlist, "Items", aa);
                wrapper.select(Items.class, user -> !noselectlist.contains(user.getColumn()));
            }

            wrapper.eq("recordid", recordid);
            Items items = itemsMapper.selectOne(wrapper);
            JSONObject json1 = JSON.parseObject(JSONObject.toJSONString(items));


            json.clear();
            jsonArray.clear();


            //jsonArray=Zxb_receivedata.fieldarray(json1,module_fieldList,"Items");
            //if (jsonArray.size()>0) json.put("maintable",jsonArray);
            json = Zxb_receivedata.maintable(json1, "Items");

            QueryWrapper<ItemsQuote> wrapperquote = new QueryWrapper<>();
            if (noSelectedlist.size() > 0) {

                String[] aa = new String[]{};
                List<String> noselectlist = Zxb_receivedata.nofieldlist(noSelectedlist, "ItemsQuote", aa);
                wrapperquote.select(ItemsQuote.class, user -> !noselectlist.contains(user.getColumn()));
            }
            wrapperquote.eq("ParentID", recordid);
            List<ItemsQuote> itemsQuoteList = itemsQuoteMapper.selectList(wrapperquote);
            //JSONArray itemquoteArray=new JSONArray();
            for (i = 0; i < itemsQuoteList.size(); i++) {
                ItemsQuote itemsQuote = itemsQuoteList.get(i);

                json1 = JSON.parseObject(JSONObject.toJSONString(itemsQuote));
                //JSONArray jsonArray1 = Zxb_receivedata.fieldarray(json1, module_fieldList, "ItemsQuote");
                JSONObject json2 = Zxb_receivedata.maintable(json1, "ItemsQuote");
                //json2.put("cpjl",jsonArray1);
                //itemquoteArray.add(json2);
                jsonArray.add(json2);

            }
            json.put("ItemsQuote", jsonArray);
            List<String> tablenamelist = new ArrayList<>();
            tablenamelist.add("Items");
            tablenamelist.add("ItemsQuote");
            json1 = Zxb_receivedata.fieldtrans(module_fieldList, tablenamelist);
            json.put("trans", json1);
//取附件名称及recorid
            QueryWrapper<SysAttachment> attachmentQueryWrapper = new QueryWrapper<>();
            attachmentQueryWrapper.eq("parentid", recordid);
            List<SysAttachment> sysAttachmentList = sysAttachmentMapper.selectList(attachmentQueryWrapper);
            JSONArray attachmentArray = new JSONArray();
            for (SysAttachment sysAttachment : sysAttachmentList) {
                JSONObject json2 = new JSONObject();
                json2.put("attachment-recordid", sysAttachment.getRecordID());
                json2.put("attachment-filename", sysAttachment.getName());
                //json2.put("attachment-storedPath",sysAttachment.getStoredPath() );
                attachmentArray.add(json2);
            }
            json.put("attachment", attachmentArray);


            return json;


        } catch (Exception e) {
            // if I/O error occurs
            e.printStackTrace();
            json.put("error","error");
            return json;
        }

    }
}
